<?php

/*
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Library General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 */

namespace EasyActionPHP\Core;

use EasyActionPHP\Controller as Controller;
use EasyActionPHP\Exception as Except;

/**
 * ActionResourceBundle - possibilita o uso de arquivos de propriedades.
 *
 * @author Flavio de Vasconcellos Correa
 * @since 2007/06/04
 * @package EasyActionPHP
 * @subpackage Core
 * @version $id$
 * @license http://www.gnu.org/copyleft/gpl.html GPL
 */
class ActionResourceBundle {

    /**
     * @var ActionResourceBundle singleton da classe.
     */
    static $instance;

    /**
     * @var Matriz par chave-valor.
     */
    private $cache;
    private $propertiesLoaded;

    /**
     * Constructor.
     */
    private function __construct() {
        $this->cache = Array();
        $this->propertiesLoaded = Array();
    }

//    private static function isLoaded() {
//        
//    }

    /**
     * Retorna a instancia da classe no padrão de projeto Singleton.
     *
     * @access public
     * @return ActionResurceBundle
     */
    static public function getInstance() {
        if (!isset(self::$instance)) {
            $cache = Controller\HttpRequest::getSessionParameter('__ACTIONRESOURCEBUNDLE');
            if (!is_null($cache)) {
                self::$instance = $cache;
            } else {
                self::$instance = new ActionResourceBundle();
            }
        }
        return self::$instance;
    }

    /**
     * Inicializa um arquivo de propriedades.
     *
     * @access public
     * @param String resourceFile
     * @return void
     */
    static public function initialize($resourceFile) {
        if (is_null($resourceFile) || !is_string($resourceFile)) {
            throw new Except\InvalidParameterException('Critical Error: parameter invalid in ActionResourceBundle::initialize');
        }
        $resource = self::getInstance();

        $resourceFileDefault .= "$resourceFile.properties";
        $resourceFileI18N .= $resourceFile . '_' . Application::getParamByName("__LOCALE") . '.properties';

        if (in_array($resourceFileDefault, $resource->propertiesLoaded) or
                in_array($resourceFileI18N, $resource->propertiesLoaded)) {
            return;
        }

        if (file_exists($resourceFileI18N)) {
            $resourceFile = $resourceFileI18N;
        } elseif (file_exists($resourceFileDefault)) {
            $resourceFile = $resourceFileDefault;
        } else {
            throw new Except\InvalidResourceFileException('Critical Error: Resource file ' . $resourceFile . ' not exists!');
        }

        if (is_readable($resourceFile)) {
            $hFile = fopen($resourceFile, 'r');
            while (!feof($hFile)) {
                $line = fgets($hFile, 4096);
                if (strlen(trim($line)) == 0 || substr(ltrim($line), 0, 1) == '#')
                    continue;
                $aTmp = explode('=', $line, 2);
                $resource->set(trim($aTmp[0]), trim($aTmp[1]));
            }
            fclose($hFile);
        }
        $resource->propertiesLoaded[] = $resourceFile;
        Controller\HttpRequest::setSessionParameter('__ACTIONRESOURCEBUNDLE', $resource);
    }

    /**
     * Esvazia o cache.
     *
     * @access public
     * @return void
     */
    public function clear() {
        $this->cache = Array();
    }

    /**
     * Remove da memória a instancia em Singleton.
     *
     * @access public
     * @return void
     */
    public function reset() {
        unset($this->instance);
    }

    /**
     * Retorna uma String associada a chave no cache.
     *
     * @access public
     * @param String key
     * @param Mixed Array assoaciado para parametros nas mensagens
     * @return String
     */
    static public function get($key, $params = false) {
        $resource = ActionResourceBundle::getInstance();
        $output = $resource->getCacheResource($key);
        if (!is_array($params))
            $params = Array($params);
        for ($i = 0; $i < count($params); $i++) {
            $output = str_replace('{' . $i . '}', $params[$i], $output);
        }
        return $output;
    }

    /**
     * Atribui um texto a uma chave no cache.
     *
     * @access public
     * @param String key
     * @param String value
     * @return void
     */
    static public function set($key, $value) {
        $resource = ActionResourceBundle::getInstance();
        $resource->setCacheResource($key, $value);
    }

    /**
     * Getter para o cache, se a chave não possuir associação, a chave é retornada.
     *
     * @access private
     * @param String key
     * @return String
     */
    private static function getCacheResource($key) {
        return array_key_exists($key, self::$instance->cache) ? self::$instance->cache[$key] : $key;
    }

    /**
     * Setter para o cache.
     *
     * @access private
     * @param String key
     * @param String value
     */
    private function setCacheResource($key, $value) {
        $this->cache[$key] = $value;
    }

}

?>